package com.lagou.edu.util;

import com.alibaba.fastjson.JSON;
import com.lagou.edu.pojo.DataSourceProp;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;

public class ModifyPropUtil {
    public static void main(String[] args) throws Exception {
        connectZk();
    }

    private static void connectZk() throws Exception {
        String zookeeperAddress = "192.168.200.200:2181";

        // 启动zookeeper
        CuratorFramework curatorClient =
                CuratorFrameworkFactory.builder().
                        connectString(zookeeperAddress) //连接地址
                        .connectionTimeoutMs(2000) //连接超时时间
                        .sessionTimeoutMs(10000) //会话超时时间
                        .retryPolicy(new ExponentialBackoffRetry(1000, 3)) //重试策略
                        .namespace("config_center") //命名空间,默认节点
                        .build();
        curatorClient.start();

        DataSourceProp dataSourceProp = new DataSourceProp();
        dataSourceProp.setDriverClassName("com.mysql.jdbc.Driver");
        dataSourceProp.setUrl("jdbc:mysql://localhost:3306/test");
        dataSourceProp.setUsername("root");
        dataSourceProp.setPassword("root");

        String content = JSON.toJSONString(dataSourceProp);

        // 创建持久节点并写入数据
        try {
            curatorClient.
                    create().
                    creatingParentsIfNeeded().
                    withMode(CreateMode.PERSISTENT).
                    forPath("/mysql",content.getBytes());
        } catch (KeeperException.NodeExistsException e) {
            curatorClient.setData().forPath("/mysql",content.getBytes());
        }

    }
}
